//
//  OrderCountCell.m
//  WorkNest
//
//  Created by qbm360 on 15/7/14.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "OrderCountCell.h"

@interface OrderCountCell ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UILabel *style;
@property (weak, nonatomic) IBOutlet UITextField *count;

@end

@implementation OrderCountCell

- (void)awakeFromNib {
    _count.delegate = self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}

- (void)setStyleString:(NSString *)styleString {
    _styleString = styleString;
    self.style.text = _styleString;
}

- (void)setCountString:(NSString *)countString {
    _countString = countString;
    self.count.text = _countString;
}

#pragma mark - action methods
- (IBAction)reduce:(id)sender {
    if ([self.count.text integerValue] == 0) {
        return;
    }
    self.count.text = [NSString stringWithFormat:@"%ld",(long)[self.count.text integerValue] - 1];
    if (self.orderCountBlock) {
        _orderCountBlock(self.index, self.count.text);
    }
}

- (IBAction)add:(id)sender {
    self.count.text = [NSString stringWithFormat:@"%ld",(long)[self.count.text integerValue] + 1];
    if (self.orderCountBlock) {
        _orderCountBlock(self.index, self.count.text);
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    textField.inputAccessoryView = view;
    view.backgroundColor = [UIColor whiteColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(SCREEN_WIDTH - 40, 0, 40, 30);
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [btn setTitle:@"完成" forState: UIControlStateNormal];
    [btn addTarget:self action:@selector(checkButton) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    [textField reloadInputViews];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if ([self.count.text isEqualToString: @"0"]) {
        self.count.text = @"";
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if ([self.count.text isEqualToString: @""]) {
        self.count.text = @"0";
    } else {
        if (self.orderCountBlock) {
            _orderCountBlock(self.index, self.count.text);
        }
    }
}

- (void)checkButton {
    [self.contentView endEditing:YES];
}

@end
